package com.javaee.controller.admin;

import com.javaee.BeforeBaseController;
import com.javaee.entity.Department;

import com.javaee.service.admin.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/departments")
public class DepartmentController extends BeforeBaseController {
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping(method = RequestMethod.GET)
    public String listDepartments(Model model, Integer currentPage) {
        if(currentPage == null)
        {
            currentPage = 1;
        }
        int totalCount = departmentService.selectCount();
        System.out.println("totalCount = " + totalCount);
        int pageSize = 5;
        int totalPage = (int)Math.ceil(totalCount*1.0/pageSize);
        List<Department> departments = departmentService.findAll((currentPage-1)*pageSize,pageSize);
        model.addAttribute("departments", departments);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        return "admin/departmentslist";
    }

    @RequestMapping("/new")
    public String newDepartmentForm(Model model) {
        model.addAttribute("department", new Department());
        return "admin/departmentnew";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String saveDepartment(Department department) {
        departmentService.save(department);
        return "redirect:/departments";
    }

    @RequestMapping("/{id}/edit")
    public String editDepartmentForm(@PathVariable Integer id, Model model) {
        Department department = departmentService.findById(id);
        model.addAttribute("department", department);
        return "admin/departmentedit";
    }

    @RequestMapping("/{id}")
    public String updateDepartment(@PathVariable Integer id, @ModelAttribute("department") Department department) {
        department.setId(id);
        departmentService.update(department);
        return "redirect:/departments";
    }

    @RequestMapping("/{id}/delete")
    public String deleteDepartment(@PathVariable Integer id) {
        departmentService.deleteById(id);
        return "redirect:/departments";
    }

    @RequestMapping("/search")
    public String searchDepartmentsByName(@RequestParam String dName,Model model) {
        List<Department> departments = departmentService.findByName(dName);
        model.addAttribute("departments", departments);
        return "admin/departmentslist";
    }
}
